<template>
	<view class="record">
		<!-- tabs -->
		<tabs @tabClick="tabClick"></tabs>
		<!-- 趋势 -->
		<view class="tendency" v-show="tabActive==0">
			<!-- 滑动 tabs -->
			<view class="scroll-tab">
				<msTabs :list="scrollList" v-model="scrollActive"></msTabs>
			</view>
			<view class="content m16">
				<!-- 图表 -->
				<uchartTools
					:chartParams="chartParams"
					:datePickerArr="monthArr|formateDatePickerArr"
					:dateTypeIndex="dateTypeIndex"
					:datePickerIndex="datePickerIndex"
					:showChart="hasData"
					@datePickerChange="datePickerChange"
					@dateTypeClick="dateTypeClick"
					ref="recordUchart">
				</uchartTools>
				<!-- 表格 -->
				<pTable 
					v-if="hasData"
					:caption="tableParams.caption"
					:heads="tableParams.heads"
					:bodys="tableParams.bodys">
				</pTable>
			</view>
			<view v-show="!hasData" class="no-data">
				暂无数据
			</view>
		</view>
		<!-- 明细 -->
		<view class="details m16" v-show="tabActive==1">
			<view class="bgw br6 mb16" v-for="(item, index) in recordArr" :key="index">
				<view class="mlr20">
					<list label="上报日期" class="bb ptb8" :value="item.readTime|dateFormate"></list>
					<list label="阀门状态" :value="item.valveStatus==0?'阀关':'阀开'" color="blue"></list>
					<list label="电池状态" :value="item.powerStatus==0?'异常':'正常'" :class="item.powerStatus==0?'red':''"></list>
					<list label="机表读数" :value="item.jxbNum+tag.unit"></list>
				</view>
			</view>
			
			<!-- 加载loading -->
			<view class="weui-loadmore" :hidden="isHideLoadMore">
				<view class="weui-loading"></view>
				<view class="weui-loadmore__tips">正在加载</view>
			</view>
			<!-- 没有数据 -->
			<view class="no-data" v-if="noData" :hidden="!isHideLoadMore">
				没有更多数据
			</view>
		</view>
	</view>
</template>

<script>
import list from '../../components/List.vue';
import msTabs from '../../components/ms-tabs/ms-tabs.vue';
import tabs from '../../components/tabs/tabs.vue';
import uchartTools from '../../components/u-charts/u-chart-tools.vue';
import pTable from '../../components/p-table/table/table.vue';
let util = require('../../utils/utils.js');
let api = require('../../utils/api.js');

export default {
	data() {
		return {
			user: {},
			tag:{},
			options:{},
			scrollList: [], // 滚动 tab
			tabActive: 0, // 顶部 tab-active
			scrollActive: 0, // 滚动 tab-active
			chartParams: {
				chartType: 'line',
				opts: {
					categories:[],
					series:[{
							name: '',
							data: [],
							color: '#8A8B97'
						}],
					xAxis: {
						// labelCount: 2 // 轴可见区域 标签数量
					},
					yAxis: {
						splitNumber: 5
					}
					
				},
				title: '用量历史统计',
				unit: '元'
			},
			tableParams: { // 明细表格
				caption: '每月用量明细',
				heads: ['月份', '用量(元)'],
				bodys: []
			},
			recordArr: [], // 抄表明细 数组
			curPageNo: 1, // 抄表明细 page
			noData: false, // 没有数据
			isHideLoadMore: true, // 是否隐藏加载更多
			monthArr: [], // 月份
			dayArr: [], // 月份天数
			datePickerIndex: new Date().getMonth(),  // 月份选择器下标
			dateTypeIndex: 1, // 日期类型
			hasData: true // 是否有数据
		};
	},
	components: {
		list,
		msTabs,
		tabs,
		pTable,
		uchartTools
	},
	filters: {
		dateFormate: function(val) { // 时间格式化
			return util.formateByTime(val);
		},
		formateDatePickerArr: function(val) { // 设置月份选择器单位
			return val.map((v,i) => {
				return v = `${v}月`;
			})
		}
	},
	watch: {
		tabActive(val) {
			if(val == 1) { // 监听顶部 tab
				this.recordArr = [];
				this.getReadMeterArr();
			}
		},
		scrollActive(val) { // 监听滚动 tab
			if(this.dateTypeIndex == 0) { // 按月查询
				let nowYear = new Date().getFullYear();
				if(nowYear == this.scrollList[this.scrollActive].title) {
					let nowMonth = new Date().getMonth();
					if(this.datePickerIndex > nowMonth) {
						this.datePickerIndex = nowMonth;
						this.$refs.recordUchart.datePickerChange({detail: {value: this.datePickerIndex.toString()}});
					}
				}
				this.getChartDataByMonth(this.datePickerIndex+1);
			} else { // 按年查询
				this.getChartDataByYear(this.scrollList[val].title);
			}
			this.getMonthArr();
		},
		dateTypeIndex(val) { // 监听日期类型
			if(val == 0) {
				this.tableParams.caption = '每日用量明细';
				this.tableParams.heads[0] = '日期';
				this.chartParams.opts.xAxis.labelCount = 1;
			} else {
				this.tableParams.caption = '每月用量明细';
				this.tableParams.heads[0] = '每月';
				this.chartParams.opts.xAxis.labelCount = 0;
			}
		}
	},
	onLoad(options) {
		this.tag = getApp().globalData.tag;
		let unit = this.tag.unit;
		this.chartParams.unit = unit;
		this.tableParams.heads =  ['月份', `用量(${unit})`];
		this.options = options;
		this.getThreeYears();
		this.getMonthArr();
	},
	onReady() {
		this.getChartDataByYear(this.scrollList[this.scrollActive].title);
	},
	methods: {
		// 最近三年
		getThreeYears() {
			let year = util.getNowTime().slice(0,4);
			for(let i = 0; i < 3; i++) {
				this.scrollList.push({title: year})
				year--;
			}
		},
		// 判断月份是否存在
		isHasMonth(listArr,month){	
			return listArr.filter((item)=>{
				return month == item.useMonth.slice(4,6);
			})
		},
		// 判断日是否存在
		isHasDay(listArr,day){	
			return listArr.filter((item)=>{
				return day == item.useDay.slice(6,8);
			})
		},
		// 计算月份长度
		getMonthArr(){
			this.monthArr = [];
			let nowYear = new Date().getFullYear();
			if(nowYear == this.scrollList[this.scrollActive].title) { // 截止当前月
				let nowMonth = new Date().getMonth() + 1;
				while(nowMonth > 0) {
					this.monthArr.unshift(nowMonth)
					nowMonth--;
				}
			} else { // 12 个月
				for(let i = 1; i < 13; i++) {
					this.monthArr.push(i)
				}
			}
		},
		// 计算天数
		getDayArr(days){
			this.dayArr = [];
			for(let i = 1; i < days + 1; i++) {
				this.dayArr.push(i);
			}
		},
		/**获取图表数据按年
		 * @param {String} year 当前年
		 */
		async getChartDataByYear(year) {
			let data = await api.getMeterUploadByYear(this.options,year);
			let listArr = data.data.listArray;
			// 清空旧数据
			this.chartParams.opts.categories = [];
			this.chartParams.opts.series[0].data = [];
			this.tableParams.bodys = [];
			
			if(listArr.length) {
				let newArray = [];
				this.hasData = true; // 显示图表
				this.chartParams.opts.yAxis.splitNumber = util.setSplitNumber(listArr, 'useNum')
				this.monthArr.forEach((v, i) => {
					let itemArr = this.isHasMonth(listArr,v);
					if(itemArr.length) {
						newArray.push(itemArr[0]);
					}else{
						newArray.push({
							useMonth:v<10?`${String(year)}0${v}`:`${String(year)+v}`,
							useNum:'0'
						})
					}
				})
				
				newArray.forEach((item, index) => {
					// 设置图表数据
					this.chartParams.opts.categories.push(item.useMonth.slice(4,6));
					this.chartParams.opts.series[0].data.push(item.useNum);
					// 设置表格数据
					this.tableParams.bodys.push([item.useMonth.slice(4,6), item.useNum===''?'无数据':item.useNum]);
				})
				console.log('返回数据',listArr)
				this.$refs.recordUchart.$refs.uchartTools.updateData(this.chartParams);
			} else {
				this.hasData = false; // 隐藏图表
			}
		},
		/**获取图表数据月统计
		 * @param {String} month 查询月
		 */
		async getChartDataByMonth(month) {
			let queryMonth = this.scrollList[this.scrollActive].title + (month<10?'0'+month:''+month);
			let date = new Date();
			let days; // 计算天数
			 // 如果是当前年份, days 截止到当前日
			if(this.scrollList[this.scrollActive].title === date.getFullYear().toString() && month === date.getMonth()+1) {
				days = date.getDate();
			} else {
				days = new Date(queryMonth.slice(0,4),queryMonth.slice(4,6),0).getDate();
			}
			
			this.getDayArr(days);
			let data = await api.getMeterUploadByMonth(this.options,queryMonth);
			let listArr = data.data.listArray;
			
			// 清空旧数据
			this.chartParams.opts.categories = [];
			this.chartParams.opts.series[0].data = [];
			this.tableParams.bodys = [];
			
			if(listArr.length) {
				let newArray = [];
				this.hasData = true; // 显示图表
				this.chartParams.opts.yAxis.splitNumber = util.setSplitNumber(listArr, 'useNum')
				this.dayArr.forEach((v, i) => {
					let itemArr = this.isHasDay(listArr,v);
					if(itemArr.length) {
						newArray.push(itemArr[0]);
					}else{
						newArray.push({
							useDay:v<10?`${queryMonth}0${v}`:`${queryMonth+v}`,
							useNum:'0'
						})
					}
				})
				
				newArray.forEach((item, index) => {
					// 设置图表数据
					this.chartParams.opts.categories.push(item.useDay.slice(6,8));
					this.chartParams.opts.series[0].data.push(item.useNum);
					// 设置表格数据
					this.tableParams.bodys.push([item.useDay.slice(6,8), item.useNum===''?'0':item.useNum]);
				})
				this.$refs.recordUchart.$refs.uchartTools.updateData(this.chartParams);
			} else {
				this.hasData = false; // 隐藏图表
			}
		},
		/**
		 * 获取上报明细
		 */
		async getReadMeterArr() {
			if(this.noData) return;
			this.isHideLoadMore = false; // 显示loading
			let data = await api.getMeterUploadData(this.options,this.curPageNo);
			this.isHideLoadMore = true; // 隐藏loading
			this.recordArr = this.recordArr.concat(data.listArray);
			if(this.curPageNo == data.totalPages) {
				this.noData = true; // 无数据提示
			} else {
				this.curPageNo++;
			}
		},
		datePickerChange(i) { // 监听月改变
			this.datePickerIndex = Number(i);
			this.getChartDataByMonth(++i);
		},
		tabClick(i) { // 切换顶部 tab
			this.tabActive = i;
		},
		dateTypeClick(i) { // 日期类型选择
			if(i == 0) { // 按月查询
				this.getChartDataByMonth(this.datePickerIndex+1);
			} else { // 按年查询
				this.getChartDataByYear(this.scrollList[this.scrollActive].title)
			}
			this.dateTypeIndex = i;
		},
	},
	// 页面触底加载更多
	onReachBottom() {
		if(this.tabActive == 1) {
			this.getReadMeterArr();
		}
	}
};
</script>

<style lang="scss">
page,.record {
	background-color: $uni-bg-color-grey;
}
</style>